<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'sex', 'age_range', 'phone', 'wechat', 'is_member',
        'address', 'contact', 'favourite', 'hate', 'industry','extra'
    ];

    public function orders(){
        return $this->hasMany(Order::class);
    }

    /**
     * @param $data
     * @param null $id
     */
    public static function dataSave($data, $id = null ): Customer
    {
        if($id){
            unset($data['created_at']);
            unset($data['updated_at']);
            self::query()->where('id',$id)->update($data);
            $customer = self::query()->find($id);
        }else{
            $customer = self::create($data);
        }
        return $customer;
    }


    public static function getByPhone($phone, $name){
        $customer = self::query()->where('phone',$phone)->first();
        // 如果联系方式写 - 则不去新建用户
        if($customer && $phone != '-'){
            $customer->name = $name;
            $customer->save();
        }else{
            $customer = self::create([
                'name'=>$name,
                'phone'=>$phone
            ]);
        }
        return $customer;
    }
}
